package com.cn.wanxi.servlet.user;

import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        0.解决乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        1.得到页面数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");//页面的验证码
//        request,session,page,application四个作用域
        String sessionCode = (String) req.getSession().getAttribute("code");//session缓存的验证码
//        如果验证码正确，则进入登陆，否则直接提示验证码错误，请重新输入
        ResultModel resultModel = new ResultModel();
        if (code.equals(sessionCode)) {
//        2.封装页面数据
            UserModel userModel = new UserModel();
            userModel.setUsername(username);
            userModel.setPassword(password);

            //        3.调用服务逻辑层

            IUserService iUserService = new UserServiceImpl();
//通过当前拿到的用户名和密码去查询，如果用户名和密码正确，则进入后台管理页面，否则重新登陆
            String result = iUserService.login(userModel);
            if (result.equals("1")) {
//                req.getSession().setAttribute("username", username);
                Jedis jedis = new Jedis();
                jedis.set(username, username);//username作为key值，不会被覆盖
                resultModel.setCode("200");
                resultModel.setResult(username);

//                Cookie cookie=new Cookie("username", username);
//                cookie.setMaxAge(200000);
//                resp.addCookie(cookie);




            } else {
                resultModel.setResult("用户名或者密码错误，请重新输入");
            }

        } else {
            resultModel.setResult("验证码输入错误，请重新输入验证码");
//            req.setAttribute("result", "验证码输入错误，请重新输入验证码");
//            req.getRequestDispatcher("/back/login.jsp").forward(req, resp);
        }
        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);
    }
}
